﻿using JuCheap.Core.Infrastructure;
using JuCheap.Core.Infrastructure.Extentions;
using JuCheap.Core.Infrastructure.Utilities;
using JuCheap.Core.IService.AppService;
using JuCheap.Core.Model;
using JuCheap.Core.Model.Message;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace JuCheap.Core.WebApi.Controllers
{
    /// <summary>
    /// 站内信服务api
    /// </summary>
    [Route("api/[controller]")]
    public class MessageController : BaseApiController
    {
        private readonly IMessageService _messageService;
        private readonly ICurrentUserService _currentUserService;

        /// <summary>
        /// ctor
        /// </summary>
        public MessageController(IMessageService messageService,
            ICurrentUserService currentUserService)
        {
            _messageService = messageService;
            _currentUserService = currentUserService;
        }

        /// <summary>
        /// 创建站内信
        /// </summary>
        [HttpPost]
        [Route("create")]
        public async Task<ActionResult<string>> Create([FromBody]MessageCreateRequestDto req)
        {
            var messageId = await _messageService.CreateAsync(req);
            return Ok(messageId);
        }

        /// <summary>
        /// 分页获取站内信
        /// </summary>
        [HttpPost]
        [Route("search")]
        public async Task<ActionResult<PagedResult<MyMessageResponseDto>>> Search([FromBody]SysMessageFilter filter)
        {
            filter.UserId = _currentUserService.GetUserId();
            var records = await _messageService.GetMyMessagesAsync(filter);
            return Ok(records);
        }

        /// <summary>
        /// 获取我未读站内信的数量
        /// </summary>
        [HttpGet]
        [Route("my-unread-message-number")]
        public async Task<ActionResult<string>> GetUnReadNumber()
        {
            var unReadNumber = await _messageService.GetMyMessageUnReadNumberAsync(_currentUserService.GetUserId());
            return Ok(unReadNumber.ToFriendlyNumber());
        }

        /// <summary>
        /// 获取站内信详细信息
        /// </summary>
        [HttpGet]
        [Route("{messageId}")]
        public async Task<ActionResult<MyMessageResponseDto>> Get([FromRoute]string messageId)
        {
            var companyDto = await _messageService.GetAsync(messageId);
            return Ok(companyDto);
        }

        /// <summary>
        /// 阅读站内信
        /// </summary>
        [HttpPost]
        [Route("read")]
        public async Task<ActionResult<bool>> Read([FromBody]IList<string> messageIds)
        {
            await _messageService.ReadAsync(messageIds, _currentUserService.GetUserId());
            return Ok(true);
        }
    }
}
